package com.sunchp.jsondb;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONReader;
import com.google.common.io.Resources;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class JsonReader {
    public static final String URL_PROTOCOL_FILE = "file";

    public static Map<String, CollectionMetaData> readObject(String jsonFile) {
        JSONReader reader = null;
        Map<String, CollectionMetaData> result = null;
        try {
            reader = new JSONReader(new FileReader(getFile(jsonFile)));
            result = new HashMap<>();

            reader.startObject();

            while (reader.hasNext()) {
                String key = reader.readString();
                JSONArray value = reader.readObject(JSONArray.class);
                result.put(key, new CollectionMetaData(key, value));
            }

            reader.endObject();
        } catch (FileNotFoundException e) {
            throw new JsonDBException("File not found: " + jsonFile, e);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        return result;
    }

    private static String getFile(String resourcePath) {
        URL resourceUrl = Resources.getResource(resourcePath);

        if (resourceUrl == null) {
            throw new JsonDBException("Resource URL must not be null");
        }

        if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {
            throw new JsonDBException("URL cannot be resolved to absolute file path because it does not reside in the file system: " + resourceUrl);
        }

        try {
            return resourceUrl.toURI().getSchemeSpecificPart();
        } catch (URISyntaxException ex) {
            //never go here
            throw new JsonDBException("URI syntax exception: " + resourceUrl, ex);
        }
    }
}
